package com.huang.Reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;
/*
*   虚引用 热河时候都有可能被gc
*
* */
class MyRef{

    @Override
    protected void finalize() throws Throwable {  //被回收前会调用
        System.out.println("我要被回收了 。。。。");
    }
}

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        weak();
    }
    public  static void phonf() throws InterruptedException {
        //虚引用  虚引用被gc入引用队列中并且调用 finalize
        ReferenceQueue referenceQueue=new ReferenceQueue();
        PhantomReference reference = new PhantomReference<>(new MyRef(), referenceQueue);

    }
    public  static void weak() throws InterruptedException {
        //弱引用  只要进行gc就会被 清理  手动gc也会被
        //  弱引用   使用在ThreadLocalmap 中的 entry用的是弱引用
        WeakReference<MyRef> weakReference = new WeakReference<>(new MyRef());
        System.out.println("前"+weakReference.get());
        System.gc();
        System.out.println("后"+weakReference.get());

    }

    public  static void soft() throws InterruptedException {
        //软引用   内存不足进行自动gc清除   否则不会被gc
        SoftReference<MyRef> myRef = new SoftReference<>(new MyRef());
        System.gc();
        System.out.println("前"+myRef.get());
        TimeUnit.SECONDS.sleep(2);


        try {
            byte[] bytes = new byte[9 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("后"+myRef.get());
        }







    }


    public  static void Strength(){
        //强引用
        MyRef myRef = new MyRef();
        System.out.println("前"+myRef);
        System.gc();
        System.out.println("后"+myRef);

    }
}
